<template>
    <ContentWrap>
        <div class="flex justify-between">
            <div class="">
                <!-- <el-select v-model="state.searchData.value" class="m-2" placeholder="请选择系统" style="width: 200px;">
                    <el-option v-for="item in state.options2" :key="item.value" :label="item.label" :value="item.value" />
                </el-select> -->
                <ElInput v-model="state.searchData.keywords" style="width: 266px;height: 32px;margin-right: 10px;"
                    placeholder="请输入菜单名称" :prefix-icon="Search" />
                <ElButton type="primary" :icon="Search" @click="onSearch">
                    查询
                </ElButton>
                <ElButton :icon="Refresh" @click="onReset">
                    重置
                </ElButton>
                <ElButton type="primary" :icon="Plus" @click="onAdd">
                    新增
                </ElButton>
            </div>
        </div>
        <div class="" style="margin-top: 25px;">
            <Table :columns="allSchemas.tableColumns" :data="dataList" :loading="loading" @register="tableRegister"
                :headerCellStyle="headerCellStyle" :rowStyle="rowStyle" />
        </div>
    </ContentWrap>
    <Dialog v-model="dialogVisible1" :title="state.title" width="500">
        <el-form ref="ruleFormRef" :model="state.ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm"
            status-icon>

            <el-form-item label="上级类目" prop="parentId">
                <el-cascader v-model="state.ruleForm.parentId" :options="state.options2" :props="props" collapse-tags
                    clearable placeholder="请选择上级类目" style="width: 100%;" />
            </el-form-item>
            <el-form-item label="菜单名称" prop="menuName">
                <el-input v-model="state.ruleForm.menuName" placeholder="请输入菜单名称" />
            </el-form-item>
            <!-- <el-form-item label="显示排序" prop="orderNum">
                <el-input-number min="0" v-model="state.ruleForm.orderNum" placeholder="请输入显示排序" />
            </el-form-item> -->
            <el-form-item label="路由地址" prop="path">
                <el-input v-model="state.ruleForm.path" placeholder="请输入路由" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="flex ">
                <ElButton @click="resetForm(ruleFormRef)">取消</ElButton>
                <ElButton type="primary" :loading="loadingAdd" @click="submitForm(ruleFormRef)">确定
                </ElButton>
            </div>
        </template>
    </Dialog>
</template>
    
<script setup lang="tsx">
import { Table } from '@/components/Table'
import { useTable } from '@/hooks/web/useTable'
import { Search, Plus, Refresh, Pointer, Star } from '@element-plus/icons-vue'
import { Dialog } from '@/components/Dialog'
import { useEmitt } from '@/hooks/event/useEmitt'
import { ElButton, ElInput, ElMessage, ElMessageBox } from 'element-plus'
import { ContentWrap } from '@/components/ContentWrap'
import { ref, reactive, unref } from "vue"
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { getMenulistApi, addMenuApi, editMenuApi, deteleMenuApi, getTreeselectApi, getMenuDetailApi } from "@/api/menu/index"
import { useI18n } from '@/hooks/web/useI18n'
const { t } = useI18n()
const props = {
    checkStrictly: true,
    value: "id",
    label: "label",
    emitPath: false
}
const dialogVisible1 = ref(false)
const loadingAdd = ref(false)
const state = reactive({
    ruleForm: {} as any,
    options2: [] as any,//职位状态下拉框
    searchData: {
        value: "",
        keywords: ""
    },
    react: true,//分页刷新
    title: "新增菜单"
})
// 表格基本信息
const crudSchemas = reactive<CrudSchema[]>([
    {
        field: 'label',
        label: t('菜单名称'),
        search: {
            component: 'Input'
        },
        form: {
            component: 'Input',
            colProps: {
                span: 24
            }
        },
        detail: {
            span: 24
        }
    },
    // {
    //     field: '所属系统',
    //     label: t('所属系统'),
    //     search: {
    //         hidden: true
    //     }
    // },
    // {
    //     field: 'weight',
    //     label: t('显示排序'),
    //     search: {
    //         hidden: true
    //     }
    // },
    // {
    //     field: 'path',
    //     label: t('路由地址'),
    //     search: {
    //         hidden: true
    //     }
    // },
    // {
    //     field: 'createTime',
    //     label: t('创建时间'),
    //     search: {
    //         hidden: true
    //     }
    // },
    {
        field: 'action',
        width: '260px',
        label: t('tableDemo.action'),
        search: {
            hidden: true
        },
        form: {
            hidden: true
        },
        detail: {
            hidden: true
        },
        table: {
            slots: {
                default: (data: any) => {
                    return (
                        <>
                            <ElButton link type="primary" onClick={() => action(data[0].row)}>
                                {t('编辑')}
                            </ElButton>
                            <ElButton link type="danger" onClick={() => delData(data[0].row)}>
                                {t('删除')}
                            </ElButton>
                        </>
                    )
                }
            }
        }
    }
])
const { tableRegister, tableState, tableMethods } = useTable({
    fetchDataApi: async () => {
        // const { currentPage, pageSize } = tableState
        const res: any = await getTreeselectApi({
            // pageNum: state.react ? 1 : unref(currentPage),
            // pageSize: unref(pageSize),
            menuName: state.searchData.keywords
        })
        console.log("菜单数据", res);
        state.react = false
        return {
            list: res.data,
            total: res.total
        }
    }
})
// 表格头部信息
const headerCellStyle: any = {
    "background": "#F2F6FC",
    "height": "48px"
}
// 
const rowStyle: any = {
    "height": "48px"
}
const { loading, dataList, total, currentPage, pageSize } = tableState

const { getList, getElTableExpose, delList } = tableMethods

getList()
useEmitt({
    name: 'getList',
    callback: (type: string) => {
        if (type === 'add') {
            currentPage.value = 1
        }
        getList()
    }
})
const { allSchemas } = useCrudSchemas(crudSchemas)
// 新增
const onAdd = () => {
    state.ruleForm = {}
    dialogVisible1.value = true
    state.title = "新增菜单"
}
const action = (row: any) => {
    console.log("编辑", row);
    getMenuDetailApi_(row.id)

    state.title = "编辑菜单"
}
// 查询
const onSearch = () => {
    console.log("查询");
    state.react = true
    getList()
}
// 重置
const onReset = () => {
    console.log("重置");
    state.searchData.value = ""
    state.searchData.keywords = ""
    state.react = true
    getList()
}

// 表单
// 校验规则
interface RuleForm {
    menuName: string,
    path: string,
    orderNum: string
}
const ruleFormRef = ref<FormInstance>()
const rules = reactive<FormRules<RuleForm>>({
    menuName: [
        { required: true, message: '请填写菜单名称', trigger: 'blur' },
        { min: 1, max: 50, message: '不超过50个字符', trigger: 'blur' },
    ],
    path: [
        { required: true, message: '请输入路由地址', trigger: 'blur' }
    ],
    orderNum: [
        { required: true, message: '请输入排序', trigger: 'blur' }
    ],

})
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            state.ruleForm.menuType = "M"
            state.ruleForm.orderNum = 9
            if (state.title == "新增菜单") {
                addMenuApi(state.ruleForm).then((res: any) => {
                    ElMessage({
                        type: 'success',
                        message: `${res.msg}`,
                    })
                    formEl.resetFields()
                    getTreeselectApi_()
                    getList()
                    dialogVisible1.value = false
                    loadingAdd.value = false
                }).catch((res: any) => {
                    ElMessage({
                        type: 'error',
                        message: `${res.msg}`,
                    })
                    loadingAdd.value = false
                })
            } else {
                editMenuApi(state.ruleForm).then((res: any) => {
                    ElMessage({
                        type: 'success',
                        message: `${res.msg}`,
                    })
                    formEl.resetFields()
                    getTreeselectApi_()
                    getList()
                    dialogVisible1.value = false
                    loadingAdd.value = false
                }).catch((res: any) => {
                    ElMessage({
                        type: 'error',
                        message: `${res.msg}`,
                    })
                    loadingAdd.value = false
                })
            }

            console.log('submit!')
        } else {
            console.log('error submit!', fields)
        }
    })
}
const resetForm = (formEl: FormInstance | undefined) => {
    dialogVisible1.value = false
    formEl.resetFields()
}
const delData = (row: any) => {
    ElMessageBox.confirm('确认删除该菜单？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        // inputPattern:,
        draggable: true,
        type: 'warning',
    }).then(() => {
        deteleMenuApi(row.id).then((res: any) => {
            getList()
            ElMessage({
                type: 'success',
                message: `${res.msg}`,
            })
        }).catch((res: any) => {
            ElMessage({
                type: 'error',
                message: `${res.msg}`,
            })
        })
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '取消操作',
        })
    })


}
const getTreeselectApi_ = async () => {
    await getTreeselectApi({}).then((res: any) => {
        console.log(res.data);

        state.options2 = res.data
    })
}

getTreeselectApi_()
const getMenuDetailApi_ = async (params) => {
    await getMenuDetailApi(params).then((res: any) => {
        console.log("xiangqing1", res.data);
        state.ruleForm.parentId = res.data.parentId
        state.ruleForm.menuName = res.data.menuName
        state.ruleForm.orderNum = res.data.orderNum
        state.ruleForm.path = res.data.path
        state.ruleForm.menuId = res.data.menuId
        dialogVisible1.value = true
    })
}
</script>
    
<style lang="less" scoped></style>